package com.tyut.util;

import com.mchange.v2.c3p0.ComboPooledDataSource;

import javax.sql.DataSource;
import java.beans.PropertyVetoException;
import java.sql.Connection;
import java.sql.SQLException;

public class C3p0Utils {
 private static ComboPooledDataSource dataSource=new ComboPooledDataSource();

 private static ThreadLocal<Connection>  tl=new ThreadLocal<>();

 /**
  * 返回连接，首先判断线程是否含有连接，如果没有，则新建连接
  */
 public static Connection getConnection() throws SQLException {
     Connection con=tl.get();
     if(con!=null) return con;
     return dataSource.getConnection();
 }
 /**
  * 开启事务
 * @throws SQLException 
  */
 public static void beginTransaction() throws SQLException{
     Connection con=tl.get();
     if(con!=null) throw new RuntimeException("已经开启了事务");
     con=getConnection();
     con.setAutoCommit(false);
     tl.set(con);
 }
 /**
 * @throws SQLException 
  *提交事务
  */
public static void commitTransaction() throws SQLException{
    Connection con=tl.get();
     if(con==null) throw new RuntimeException("没有事务");
     con.commit();
     con.close();
     tl.remove();
 }
/**
 * @throws SQLException 
 * 回滚事务
 */
public static void rollbackTransaction() throws SQLException{
    Connection con=tl.get();
     if(con==null) throw new RuntimeException("没有事务");
     con.rollback();
     con.close();
     tl.remove();
}
/**
 * 判断是否能够关闭连接，如果不属于事务那么就关闭。
 */
 public static void releaseConnection(Connection connection) throws SQLException{
     Connection con=tl.get();
     if(con==null) connection.close();
     if(con!=connection) connection.close();
 }
 /**
  * 返回连接池对象
  */
 public static DataSource getDateSource(){
     /*
      * 使用四大参数组件 连接数据库
      */
     try {
         dataSource.setDriverClass("com.mysql.jdbc.Driver");
     } catch (PropertyVetoException e) {
         e.printStackTrace();
     }

     dataSource.setJdbcUrl("jdbc:mysql://fantj.top:3306/stu_apt_sys");

     dataSource.setUser("root");

     dataSource.setPassword("root");

     //池配置
     dataSource.setInitialPoolSize(10);
     dataSource.setAcquireIncrement(5);
     dataSource.setMaxPoolSize(20);
     dataSource.setMinPoolSize(5);
   return dataSource;
 
 }
}